package drds.global_transaction.resource_manager.sql_recognizer;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.util.JdbcUtils;
import drds.global_transaction.resource_manager.sql_recognizer.impl.DeleteSqlRecognizer;
import drds.global_transaction.resource_manager.sql_recognizer.impl.InsertSqlRecognizer;
import drds.global_transaction.resource_manager.sql_recognizer.impl.SelectForUpdateSqlRecognizer;
import drds.global_transaction.resource_manager.sql_recognizer.impl.UpdateSqlRecognizer;

import java.util.List;

public class SqlVisitorFactory
{

	public static SqlRecognizer get(String sql)
	{
		List<SQLStatement> sqlStatementList = SQLUtils.parseStatements(sql, JdbcUtils.MYSQL);
		if (sqlStatementList == null || sqlStatementList.size() != 1)
		{
			throw new UnsupportedOperationException("xxx");
		}
		SqlRecognizer sqlRecognizer = null;
		SQLStatement sqlStatement = sqlStatementList.get(0);
		if (sqlStatement instanceof SQLInsertStatement)
		{
			sqlRecognizer = new InsertSqlRecognizer(sql, sqlStatement);
		} else if (sqlStatement instanceof SQLUpdateStatement)
		{
			sqlRecognizer = new UpdateSqlRecognizer(sql, sqlStatement);
		} else if (sqlStatement instanceof SQLDeleteStatement)
		{
			sqlRecognizer = new DeleteSqlRecognizer(sql, sqlStatement);
		} else if (sqlStatement instanceof SQLSelectStatement)
		{
			sqlRecognizer = new SelectForUpdateSqlRecognizer(sql, sqlStatement);
		}
		return sqlRecognizer;
	}

	public static void main(String[] args) throws Throwable
	{
		String sql = "update material_inventory SET version = ? WHERE is_deleted = 0 and id = ? and version = ?";

		for (int i = 0; i < 100; i++)
		{
			long begin = System.currentTimeMillis();
			SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
			long end = System.currentTimeMillis();
			System.out.println(String.format("SQL:[%s] parser too slow, cost [%d] ms.", sql, (end - begin)));
		}

	}
}
